<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="50px"
    >
      <el-form-item label="班次" prop="shift">
        <el-select
          placeholder="请选择班次"
          v-model="queryParams.shift"
          style="width: 160px"
          clearable
          @change="handleQuery"
        >
          <el-option label="白班" value="1"></el-option>
          <el-option label="夜班" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="台位" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          show-word-limit
          placeholder="请输入台位"
          maxlength="10"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px"
        />
      </el-form-item>
      <el-form-item label="股道" prop="trackName">
        <el-input
          v-model="queryParams.trackName"
          show-word-limit
          placeholder="请输入股道"
          maxlength="10"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px"
        />
      </el-form-item>
      <el-form-item label="1列位车号" label-width="80px" prop="oneColumn">
        <el-input
          v-model="queryParams.oneColumn"
          show-word-limit
          placeholder="请输入1列位车号"
          maxlength="15"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px"
        />
      </el-form-item>
      <el-form-item label="2列位车号" label-width="80px" prop="twoColumn">
        <el-input
          v-model="queryParams.twoColumn"
          show-word-limit
          placeholder="请输入2列位车号"
          maxlength="15"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 160px"
        />
      </el-form-item>
      <el-form-item label="长编组重联" label-width="90px" prop="isLong">
        <el-select
          placeholder="请选择"
          v-model="queryParams.isLong"
          style="width: 160px"
          clearable
          @change="handleQuery"
        >
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <!-- <el-date-picker v-model="dateRange" style="width:220px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker> -->
        <el-date-picker
          v-model="queryParams.jobDate"
          type="date"
          placeholder="选择日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <div class="searchReset">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
          <el-button icon="el-icon-download" size="mini" @click="exportQuery"
            >导出</el-button
          >
        </div>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <div
      :class="eleTabTop <= 85 ? 'eleTab' : ''"
      class="informationTab"
      ref="eleTab"
    >
      <el-table
        v-loading="loading"
        :data="workPlanList"
        :header-cell-style="{ 'text-align': 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="55" />
        <el-table-column label="班次" align="center" prop="shift" />
        <el-table-column
          label="日期"
          align="center"
          prop="jobDate"
          width="180"
        />
        <el-table-column label="台位" align="center" prop="positionName" />
        <el-table-column label="股道" align="center" prop="trackName" />
        <el-table-column
          label="1列位"
          align="center"
          prop="oneColumn"
          min-width="140"
        >
          <template slot-scope="scope">
            <div
              @click="
                OneColmu(scope.row.oneColumn, scope.row.id, scope.row.planGuid)
              "
            >
              {{ scope.row.oneColumn }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="2列位"
          align="center"
          prop="twoColumn"
          min-width="140"
        >
          <template slot-scope="scope">
            <div
              @click="
                twoColumn(scope.row.twoColumn, scope.row.id, scope.row.planGuid)
              "
            >
              {{ scope.row.twoColumn }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="长编组重联"
          align="center"
          prop="isLong"
          min-width="120"
        />
        <el-table-column label="班组卡控" align="center" min-width="150">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.teamOnoff"
              active-value="1"
              inactive-value="0"
              disabled
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="right"
          class-name="small-padding fixed-width"
          width="370px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              class="operite"
              icon="el-icon-view"
              size="mini"
              type="text"
              @click="handleSettingFirstTime(scope.row)"
              >1列位时间
            </el-button>
            <el-button
              class="operite"
              icon="el-icon-view"
              size="mini"
              type="text"
              @click="handleSettingSecondTime(scope.row)"
              >2列位时间
            </el-button>
            <el-button
              class="operite"
              icon="el-icon-view"
              size="mini"
              type="text"
              @click="handleFirst(scope.row)"
              >1列位班组
            </el-button>
            <el-button
              class="operite"
              icon="el-icon-view"
              size="mini"
              type="text"
              @click="handleSecond(scope.row)"
              >2列位班组
            </el-button>
            <!-- <el-button class="operite" icon='el-icon-view' size="mini" type="text" v-if="scope.row.isLong == '是'"
              @click="handleWorkplan(scope.row)">作业班组
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 一二列位弹框 -->
    <el-dialog
      title="入库作业"
      :visible.sync="OnesShowCar"
      width="1200px"
      append-to-body
    >
      <div style="display: flex; justify-content: space-between">
        <div style="margin: 10px 0; font-size: 18px">车号：{{ carCode }}</div>
        <div>
          <el-button type="primary" size="mini" @click="handleExport"
            >导出</el-button
          >
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="供电预检" name="first"></el-tab-pane>
        <el-tab-pane label="断电作业" name="second"></el-tab-pane>
        <el-tab-pane label="供电检修" name="third"></el-tab-pane>
      </el-tabs>
      <div style="height: 70vh; overflow-y: scroll; padding-right: 15px">
        <el-table :data="enterList">
          <el-table-column
            label="检修班组"
            align="center"
            prop="workTeamName"
            min-width="180"
            show-overflow-tooltip=""
          />
          <el-table-column
            label="开始时间"
            align="center"
            prop="startTime"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="插号志人员"
            align="center"
            prop="insertPersonName"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="时长"
            align="center"
            prop="duration"
            min-width="180"
            show-overflow-tooltip=""
          />
          <el-table-column
            label="结束时间"
            align="center"
            prop="endTime"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="撤号志人员"
            align="center"
            prop="removePersonName"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 无车 -->
    <el-dialog
      title="入库作业"
      :visible.sync="NoneShowCar"
      width="1200px"
      append-to-body
    >
      <div style="display: flex; justify-content: space-between">
        <div style="margin: 10px 0; font-size: 18px">车号：{{ carCode }}</div>
        <div>
          <el-button type="primary" size="mini" @click="handleExport"
            >导出</el-button
          >
        </div>
      </div>

      <el-tabs v-model="NoneactiveName">
        <el-tab-pane label="无车作业" name="first"></el-tab-pane>
      </el-tabs>
      <div style="height: 70vh; overflow-y: scroll; padding-right: 15px">
        <el-table :data="noCarList">
          <el-table-column
            label="检修班组"
            align="center"
            prop="workTeamName"
            min-width="180"
            show-overflow-tooltip=""
          />
          <el-table-column
            label="开始时间"
            align="center"
            prop="startTime"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="插号志人员"
            align="center"
            prop="insertPersonName"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="时长"
            align="center"
            prop="duration"
            min-width="180"
            show-overflow-tooltip=""
          />
          <el-table-column
            label="结束时间"
            align="center"
            prop="endTime"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
          <el-table-column
            label="撤号志人员"
            align="center"
            prop="removePersonName"
            min-width="180"
            show-overflow-tooltip=""
          >
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <el-dialog
      :title="workTitle"
      :visible.sync="workGroupshow"
      width="800px"
      append-to-body
    >
      <el-table v-loading="workloading" :data="workListGroup" height="60vh">
        <el-table-column label="序号" align="center" type="index" width="55" />
        <el-table-column label="班组名称" align="center" prop="teamName" />
      </el-table>
    </el-dialog>

    <el-dialog
      :title="timeTitle"
      :visible.sync="settingTime"
      width="700px"
      append-to-body
    >
      <el-form :model="TimeForm" size="small" label-width="150px">
        <el-form-item label="开始时间" prop="oneStartTime" v-if="onesFlag">
          <el-date-picker
            v-model="TimeForm.oneStartTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="oneEndTime" v-if="onesFlag">
          <el-date-picker
            v-model="TimeForm.oneEndTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="开始时间" prop="twoStartTime" v-if="twosFlag">
          <el-date-picker
            v-model="TimeForm.twoStartTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="twoEndTime" v-if="twosFlag">
          <el-date-picker
            v-model="TimeForm.twoEndTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  workHistoryList,
  getWorkPlan,
  delWorkPlan,
  addWorkPlan,
  updateWorkPlan,
  listChoice,
  listbycar,
  PlanTeamlistvo,
  gettimeInfo,
  createXLSlIST
} from "@/api/planManage/planManage";
import { listPosition } from "@/api/baseData/position";
import { listTrack } from "@/api/baseData/track";

export default {
  name: "WorkPlan",
  data() {
    return {
      onesFlag: false,
      twosFlag: false,
      timeTitle: "",
      // 选择时间对象
      TimeForm: {
        id: "",
        startTime: "",
        endTime: "",
      },
      // 设置时间弹框
      settingTime: false,
      workListGroup: [],
      workloading: true,
      workGroupshow: false,
      workTitle: "",
      eleTabTop: 0,
      //表格容器eleTabTop距浏览器顶部距离
      complete: 1,
      planGuid: "",
      oneId: "",
      noCarList: [],
      oneParams: {
        carCode: null,
        complete: null,
        type: null,
        workPlanId: null,
      },
      NoneactiveName: "first",
      NoneShowCar: false,
      oneTotal: 0,
      carCode: "",
      enterList: [],
      activeName: "first",
      OnesShowCar: false,
      eleTabTop: 0, //表格容器eleTabTop距浏览器顶部距离
      choiceList: [], // 列位下拉框
      positionList: [], // 台位
      trackList: [], // 股道
      dateRange: [], // 日期范围
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 作业计划表格数据
      workPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        oneColumn: null,
        twoColumn: null,
        trackName: null,
        positionName: null,
        startTime: null,
        endTime: null,
        shift: null,
        isLong: null,
        jobDate: null,
      },
      // 表单参数
      form: {
        jobDate: "", // 日期
        shift: "1", // 白班或者夜班
        workPlanList: [],
      },
      openEdit: false, // 修改弹窗
      editForm: {
        positionId: "",
        positionName: "",
        trackId: "",
        trackName: "",
        oneColumnId: null,
        twoColumnId: null,
        isLong: "",
        shift: "",
        id: null,
      },
      // 表单校验
      rules: {
        jobDate: [
          {
            required: true,
            message: "日期不能为空",
            trigger: "blur",
          },
        ],
        shift: [
          {
            required: true,
            message: "班次不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    // this.getDict() // 获取新增页面字典
  },
  mounted() {
    // 滚动条的获取
    this.handleScrollx();
    window.addEventListener("scroll", this.handleScrollx, true);
  },
  activated() {
    //获取表格容器距页面头部的距离
    this.handleScrollx();
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScrollx, true);
  },

  methods: {
    exportQuery() {
      let id = this.ids.join(",")
      this.downloadsList(
        `workRecord/workRecord/createXLS2/${id}`,
        {},
        `workPlan_${new Date().getTime()}.xls`
      );
    },
   downloadFile(url) {
  const link = document.createElement('a');
  link.href = url;
  link.download = 'filename.ext'; // 可以指定文件名和扩展名
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
},


    handleSettingFirstTime(row) {
      this.timeTitle = "一列位时间";
      this.complete = 1;
      this.onesFlag = true;
      this.twosFlag = false;
      this.timeInfo(row.id);

    },
    handleSettingSecondTime(row) {
      this.twosFlag = true;
      this.onesFlag = false;
      this.timeTitle = "二列位时间";
      this.complete = 2;
      this.timeInfo(row.id);
    },
    timeInfo(id) {
      gettimeInfo({
        id: id,
        complete: this.complete,
      }).then((res) => {
        this.settingTime = true;
        this.TimeForm = res.data;
      });
    },
    handleFirst(row) {
      this.workTitle = "1列位班组";
      this.workGroupshow = true;
      this.getdatas(row.id, 1);
    },
    getdatas(id, complete) {
      this.workListGroup = [];
      PlanTeamlistvo({
        workPlanId: id,
        complete: complete,
      }).then((res) => {
        this.workListGroup = res.rows;
        this.workloading = false;
      });
    },
    handleSecond(row) {
      this.workTitle = "2列位班组";
      this.workGroupshow = true;
      this.getdatas(row.id, 2);
    },
    handleWorkplan(row) {
      this.workTitle = "作业班组";
      this.workGroupshow = true;
      this.getdatas(row.id, 0);
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
      if (this.activeName == "first") {
        this.oneParams.type = 1;
      } else if (this.activeName == "second") {
        this.oneParams.type = 2;
      } else if (this.activeName == "third") {
        this.oneParams.type = 3;
      }
      this.getlistbycar();
    },
    twoColumn(carCode, id, planGuid) {
      if (carCode == "无车") {
        this.NoneactiveName = "first";
        this.oneParams.type = 4;
        this.NoneShowCar = true;
      } else {
        this.activeName = "first";
        this.oneParams.type = 1;
        this.OnesShowCar = true;
      }

      this.carCode = carCode;
      this.oneId = id;
      this.planGuid = planGuid;
      this.complete = 2;
      this.oneParams.carCode = carCode;
      this.oneParams.workPlanId = id;
      this.oneParams.complete = 2;

      this.getlistbycar();
    },
    OneColmu(carCode, id, planGuid) {
      if (carCode == "无车") {
        this.NoneactiveName = "first";
        this.oneParams.type = 4;
        this.NoneShowCar = true;
      } else {
        this.activeName = "first";
        this.oneParams.type = 1;
        this.OnesShowCar = true;
      }
      this.carCode = carCode;
      this.oneId = id;
      this.planGuid = planGuid;
      this.complete = 1;
      this.oneParams.carCode = carCode;
      this.oneParams.workPlanId = id;
      this.oneParams.complete = 1;
      this.getlistbycar();
    },
    getlistbycar() {
      listbycar(this.oneParams).then((res) => {
        if (this.oneParams.carCode == "无车") {
          this.noCarList = res.rows;
        } else {
          this.enterList = res.rows;
        }
      });
    },
    //获取表格容器距页面头部的距离
    handleScrollx() {
      this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top;
    },
    /** 查询作业计划列表 */
    getList() {
      this.loading = true;
      workHistoryList(this.addDateRange(this.queryParams)).then((response) => {
        this.workPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.jobDate = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 获取新增页面字典
    // async getDict() {
    //   // 列位下拉框
    //   let choiceRes = await listChoice()
    //   if (choiceRes.code === 200) {
    //     this.choiceList = choiceRes.rows;
    //   }
    //   // 台位
    //   let positionRes = await listPosition()
    //   if (positionRes.code === 200) {
    //     this.positionList = positionRes.rows;
    //   }
    //   // 股道
    //   let trackRes = await listTrack()
    //   if (trackRes.code === 200) {
    //     this.trackList = trackRes.rows;
    //   }
    // },
    // 设置添加表格数据
    setWorkPlanList() {
      let resArr = [];
      this.positionList.map((itemP) => {
        this.trackList.map((itemT) => {
          let infoObj = {
            positionId: itemP.id,
            positionName: itemP.name,
            trackId: itemT.id,
            trackName: itemT.name,
            oneColumnId: null,
            twoColumnId: null,
            isLong: "0",
          };
          resArr.push(infoObj);
        });
      });
      this.form.workPlanList = [...resArr];
      let getParams = JSON.parse(localStorage.getItem("setParams"));
      if (getParams && this.title === "添加计划") {
        this.form.workPlanList = getParams.workPlanList;
      }
    },
    // 合并表格行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let listLength = this.trackList.length;
      if (columnIndex === 0) {
        if (rowIndex % listLength === 0) {
          return {
            rowspan: listLength,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.title === "添加计划") {
        if (localStorage.getItem("setParams")) {
          let getParams = JSON.parse(localStorage.getItem("setParams"));
          this.form.shift = getParams.shift;
          this.form.jobDate = getParams.jobDate;
        }
      } else {
        this.reset();
      }
      this.setWorkPlanList(); // 设置添加表格数据
      this.open = true;
      this.title = "添加计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetEdit();
      const id = row.id || this.ids;
      getWorkPlan(id).then((response) => {
        this.editForm = response.data;
        this.openEdit = true;
        this.title = "修改计划";
      });
    },
    // 取消按钮
    cancel() {
      if (this.title === "添加计划") {
        let setParams = {
          shift: this.form.shift,
          jobDate: this.form.jobDate,
          workPlanList: this.form.workPlanList,
        };
        localStorage.setItem("setParams", JSON.stringify(setParams));
      }
      this.open = false;
      this.openEdit = false;
      // this.reset();
      this.resetEdit();
    },
    // 表单重置
    reset() {
      this.form = {
        jobDate: "", // 日期
        shift: "1", // 白班或者夜班
        workPlanList: [
          {
            id: null,
            jobDate: null,
            shift: null,
            positionId: null,
            positionName: null,
            trackId: null,
            trackName: null,
            oneColumnId: null,
            oneColumn: null,
            twoColumnId: null,
            twoColumn: null,
            complete: null,
            isLong: null,
            startTime: null,
            endTime: null,
          },
        ],
      };
      this.resetForm("form");
    },
    // 重置编辑表单
    resetEdit() {
      this.editForm = {
        positionId: "",
        positionName: "",
        trackId: "",
        trackName: "",
        oneColumnId: null,
        twoColumnId: null,
        isLong: "",
        shift: "",
        id: null,
      };
      this.resetForm("editForm");
    },
    /** 提交按钮 */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (formName === "editForm") {
            updateWorkPlan(this.editForm).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.openEdit = false;
              this.getList();
            });
          } else {
            this.form.workPlanList.forEach((item) => {
              item.shift = this.form.shift;
              item.jobDate = this.form.jobDate;
            });
            addWorkPlan(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              localStorage.removeItem("setParams");
              this.reset();
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除作业计划？")
        .then(function () {
          return delWorkPlan(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */

    handleExport() {
      this.downloads(
        `workRecord/workRecord/createXLS?workPlanId=${this.oneId}&planGuid=${this.planGuid}&carCode=${this.carCode}&complete=${this.complete}`,
        {
          workPlanId: this.oneId,
          planGuid: this.planGuid,
          carCode: this.carCode,
          complete: this.complete,
        },
        `workPlan_${new Date().getTime()}.xls`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tabs {
  height: 48px;
}

::v-deep .el-tabs__item {
  font-weight: 600 !important;
  font-size: 16px;
}

::v-deep .eleTab {
  .s {
    justify-content: space-around;
  }

  .borders {
    border-bottom: 1px solid !important;
  }
}

::v-deep.hideSidebar {
  .eleTab {
    .el-table__header-wrapper {
      padding-left: 249px !important;
    }
  }
}
</style>
